<template>
  <div class="talkContent">
    <button @click="getTalk">获取一句话</button>
    <ul>
      <li v-for="item in talkList" :key="item.id">
        {{ item.title }}
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts" name="LoveTalk">
import { ref, reactive } from "vue";
import axios from "axios";
import { nanoid } from "nanoid";
import { useLoveTalkStore } from "@/store/loveTalk";
import { storeToRefs } from "pinia";

// 定义talk对象的类型
interface Talk {
  id: string;
  title: string;
}

const loveTalkStore = useLoveTalkStore();
console.log("loveTalkStore", loveTalkStore);
const { talkList } = storeToRefs(loveTalkStore);
console.log("talkList", talkList);
// let talkList = reactive<Talk[]>([]);
// async function getTalk() {
//   // 使用代理路径解决跨域问题
//   let result = await axios.get("/api/api/rand.qinghua?format=json");
//   //axios返回的是promise对象，加上await会等待promise对象返回结果
//   //下面的写法是连续解构赋值+重命名
//   // let {data:{content:title}} = await axios.get(
//   //   "/api/api/rand.qinghua?format=json"
//   // );
//   console.log(result);
//   let obj = {
//     id: nanoid(),
//     title: result.data.content, //可以直接简写 title
//   };
//   console.log(obj);
//   //放到数组第一个
//   talkList.unshift(obj);
// }

loveTalkStore.$subscribe(async (mutation, state) => {
  console.log("$subscribe订阅的数据发生变化了" + mutation, state);
  localStorage.setItem("talkList", JSON.stringify(state.talkList));
});
function getTalk() {
  loveTalkStore.getATalk();
}
</script>

<style scoped>
.talkContent {
  background: #cacaca;
  width: 100%;
  margin: 0 auto;
  text-align: center;
  padding: 10px;
}
</style>
